//
//  AlbumDataSource.m
//  PhotoKitDemo
//
//  Created by 红沙尘 on 17/5/3.
//  Copyright © 2017年 红沙尘. All rights reserved.
//

#import "AlbumDataSource.h"

@interface AlbumDataSource ()



@end

@implementation AlbumDataSource

+ (AlbumDataSource *)shareAlbumDataSource:(void(^)())completion
{
    static AlbumDataSource *userInfo ;
    static dispatch_once_t USERINFO_INIT ;
    dispatch_once(&USERINFO_INIT, ^{
        userInfo = [[AlbumDataSource alloc] initAlbumCompletion:completion];
    });
    
    return userInfo;
}

- (id)initAlbumCompletion:(void(^)())completion {
    self = [super init];
    
    if (self) {
        
        __weak AlbumDataSource *weakself = self;
        
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) {
                //code
                weakself.options = [[PHImageRequestOptions alloc] init];//请求选项设置
                weakself.options.resizeMode = PHImageRequestOptionsResizeModeExact;//自定义图片大小的加载模式
                weakself.options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
                weakself.options.synchronous = YES;//是否同步加载
                
                
                //容器类
                /*
                 PHAssetMediaType：
                 PHAssetMediaTypeUnknown = 0,//在这个配置下，请求不会返回任何东西
                 PHAssetMediaTypeImage   = 1,//图片
                 PHAssetMediaTypeVideo   = 2,//视频
                 PHAssetMediaTypeAudio   = 3,//音频
                 */
                weakself.assets = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil]; //得到所有图片
                
                completion();
            }
        }];
        

    }
    
    return self;
}

#pragma mark  保存照片到相册

- (void)saveImage:(UIImage *)image
          toAlbum:(NSString *)album
         complete:(void(^)(PHFetchResult<PHAsset *> * result, NSError *error) )complete {
    
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
    //请求/检查访问权限
    //如果用户还没有做出选择，会自动弹框，用户对弹框做出选择后才会调用block
    //如果之前做过选择，会直接执行调用block
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (status == PHAuthorizationStatusDenied) {//用户拒绝当前APP访问相册
                if (oldStatus != PHAuthorizationStatusNotDetermined) {
                    //提醒用户打开开关
                }
            }else if (status == PHAuthorizationStatusAuthorized) {//用户允许当前APP访问相册
                
                [self saveImage:image
                      intoAlbum:album
                       complete:^(PHFetchResult<PHAsset *> *result, NSError *error)
                 {
                     complete(result,error);
                 }];
            }else if (status == PHAuthorizationStatusRestricted) {//无法访问相册
                //因系统原因无法访问相册
            }
        });
    }];
    
}
//保存照片到自定义相册
- (void)saveImage:(UIImage *)image
        intoAlbum:(NSString *)album
         complete:(void(^)(PHFetchResult<PHAsset *> * result, NSError *error) )complete {
    //保存图片到相机胶卷
    PHFetchResult<PHAsset *> *createdAsset = [self assetWithImage:image];
    if (createdAsset == nil) {
        //保存照片失败
        
        complete(nil,nil);
        return;
    }
    //获得相册
    PHAssetCollection *collection = [self albumWithNamed:album];
    if (collection == nil) {
        //创建相册失败
        
        complete(nil,nil);
        return;
    }
    //把刚才添加到相机胶卷的照片放到自定义相册
    NSError *error = nil;
    
    [[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{
        
        PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
        [request insertAssets:createdAsset atIndexes:[NSIndexSet indexSetWithIndex:0]];
        
        complete(createdAsset,nil);
        
    } error:&error];
    
    if (error) {
        //保存图片失败
        complete(nil,error);
        return;
    }
}
//返回刚才保存到相机胶卷的照片
- (PHFetchResult<PHAsset *> *)assetWithImage:(UIImage *)image{
    
    NSError *error = nil;
    //保存照片到相机胶卷
    __block NSString * createdID = nil;
    [[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^
     {
         createdID = [PHAssetChangeRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
         
     } error:&error];
    
    if (error) return nil;
    
    return [PHAsset fetchAssetsWithLocalIdentifiers:@[createdID] options:nil];
    
}
//当前APP对应的相册
- (PHAssetCollection *)albumWithNamed:(NSString *)albumNamed{
    
    //获取应用的名字
    NSString *title = albumNamed;
    //抓取所有的自定义相册
    PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    //查找当前APP对应的自定义相册
    for (PHAssetCollection *collection in collections) {
        if ([collection.localizedTitle isEqualToString:title]) {
            return collection;
        }
    }
    /** 当前APP对应的自定义相册没有被创建过 **/
    NSError *error = nil;
    __block NSString *createdCollectionID;
    //创建一个相册,拿到相册的唯一标识符
    [[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{
        createdCollectionID = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title].placeholderForCreatedAssetCollection.localIdentifier;
    } error:&error];
    
    if (error) return nil;
    
    //根据相册的唯一标识符拿到相册
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createdCollectionID] options:nil].firstObject;
    
}

@end
